#if !UNITY_3_5 && !UNITY_FLASH
#define DYNAMIC_FONT
#endif

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace WXB
{
    public class Fonts
    {
        static public UIFont GetFont(string name)
        {
            if (GetDefaultFont().name == name)
                return DefaultFont;

            return null;
        }

        static public UIFont GetDefaultFont()
        {
            if (DefaultFont == null)
                DefaultFont = UnityEngine.Object.FindObjectOfType<UIFont>();
            return DefaultFont;
        }

        static UIFont DefaultFont = null;

        static public float GetTextExtent(UIFont font, int fontSize, ref string tex)
        {
            if (string.IsNullOrEmpty(tex))
                return 0f;

            float width = GetFontWidth(font, fontSize, tex[0], 0);
            for (int i = 1; i < tex.Length; ++i)
            {
                width += GetFontWidth(font, fontSize, tex[i], tex[i] - 1);
            }

            return width;
        }

        static public float GetCharExtent(UIFont font, int fontSize, char c)
        {
            return GetFontWidth(font, fontSize, c, 0);
        }

        static CharacterInfo mTempChar;

        static public float GetFontWidth(UIFont font, int fontSize, int ch, int prev)
        {
            if (!font.isDynamic)
            {
                BMGlyph bmg = font.bmFont.GetGlyph(ch);

                if (bmg != null)
                {
                    return NGUIText.fontScale * ((prev != 0) ? bmg.advance + bmg.GetKerning(prev) : bmg.advance);
                }
            }
#if DYNAMIC_FONT
            else
            {
                if (font.dynamicFont.GetCharacterInfo((char)ch, out mTempChar, fontSize, font.dynamicFontStyle))
                    return Mathf.Round(mTempChar.width * NGUIText.fontScale * NGUIText.pixelDensity);
            }
#endif
            return 0f;
        }
    }
}